import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pink_app/style/color.dart';
import 'package:video_player/video_player.dart';
import "bili_video_controller.dart";
import '../style/decoration.dart';

// 视频播放器组合
class VideoPlayer extends StatefulWidget {
  final String url; // 播放地址
  final double aspectRatio; // 视频播放器比
  final bool autoPlay; // 是否自动播放
  final String placeImgUrl; // 占位Widget

  const VideoPlayer(this.url, this.placeImgUrl,
      {Key key, this.autoPlay = false, this.aspectRatio = 16 / 9})
      : super(key: key);

  @override
  _VideoPlayerState createState() => _VideoPlayerState();
}

class _VideoPlayerState extends State<VideoPlayer> {
  VideoPlayerController _vController;
  ChewieController _cController;
  double _playerHeight; // 播放器高度
  double _playerWidth; // 播放器宽度

  // 初始生命周期
  @override
  void initState() {
    super.initState();
    _vController = VideoPlayerController.network(widget.url);
    _cController = ChewieController(
        placeholder: SizedBox.expand(
            child: Image.network(widget.placeImgUrl, fit: BoxFit.cover)),
        allowPlaybackSpeedChanging: false, // 不允许改变视频速度
        videoPlayerController: _vController,
        materialProgressColors: ChewieProgressColors(
            playedColor: mainThemeColor, bufferedColor: lightGrayTextColor),
        customControls: BiliVideoController(
          showBigPlayIcon: false,
          bottomGradient: blackLinearGradient(),
          overlayUI: _buildOverlayUI(),
        ),
        autoPlay: widget.autoPlay,
        aspectRatio: widget.aspectRatio);
  }

  // 废弃生命周期
  @override
  void dispose() {
    _vController.dispose();
    _cController.dispose();
    super.dispose();
  }

  // 上浮层UI
  Container _buildOverlayUI() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 5),
      decoration: BoxDecoration(gradient: blackLinearGradient(fromTop: true)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          BackButton(color: Colors.white),
          Row(
            children: <Widget>[
              Icon(Icons.live_tv_rounded, color: Colors.white, size: 20),
              Padding(
                  padding: EdgeInsets.only(left: 15),
                  child: Icon(Icons.more_vert_rounded,
                      color: Colors.white, size: 20))
            ],
          )
        ],
      ),
    );
  }

  // 计算容器宽高
  void calPlayerSize(BuildContext ctx) {
    setState(() {
      _playerWidth = MediaQuery.of(ctx).size.width;
      _playerHeight = _playerWidth / widget.aspectRatio;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_playerWidth == null || _playerHeight == null)
      calPlayerSize(context); // 初始化时计算容器宽高
    return Container(
      width: _playerWidth,
      height: _playerHeight,
      child: Chewie(
        controller: _cController,
      ),
    );
  }
}
